package com.yanq.liancar.activity;
/*
 *  @创建者     liyan
 *  @创建时间   2018/9/17  14:20
 *  @描述       ${TODO}
 */
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.Json1Bean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.Utils;

import org.json.JSONArray;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;



public class SmallBPermissionApplicationActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right2)
    ImageView ivRight2;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.common_toolbar)
    Toolbar commonToolbar;
    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.img_rightgo6)
    ImageView imgRightgo6;
    @BindView(R.id.img_license)
    ImageView imgLicense;
    @BindView(R.id.rl_license)
    RelativeLayout rlLicense;
    @BindView(R.id.img_rightgo2)
    ImageView imgRightgo2;
    @BindView(R.id.tv_shopname)
    EditText tvShopname;
    @BindView(R.id.rl_shopname)
    RelativeLayout rlShopname;
    @BindView(R.id.img_rightgo3)
    ImageView imgRightgo3;
    @BindView(R.id.et_shopphone)
    EditText etShopphone;
    @BindView(R.id.rl_shopphone)
    RelativeLayout rlShopphone;
    @BindView(R.id.img_rightgo4)
    ImageView imgRightgo4;
    @BindView(R.id.tv_shopaddress)
    TextView tvShopaddress;
    @BindView(R.id.tv_subm)
    TextView tvSubm;
    @BindView(R.id.rl_shopaddress)
    RelativeLayout rlShopaddress;
    @BindView(R.id.img_rightgo5)
    ImageView imgRightgo5;
    @BindView(R.id.tv_shopabstract)
    EditText tvShopabstract;
    @BindView(R.id.rl_shopabstract)
    RelativeLayout rlShopabstract;
    @BindView(R.id.img_zheng)
    ImageView imgZheng;
    @BindView(R.id.img_fan)
    ImageView imgFan;

    private List<String> options1Items = new ArrayList<>();
    private List<Json1Bean> options1Items1 = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private int status;
    private Uri resultUri;
    private File file1,file2,file3;
    private List<File> mFiles=new ArrayList<>();
    private Map<String,File> mFileMap=new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permissionapplication);
        Utils.setStatusBar(this, true,false);
        ButterKnife.bind(this);
        mTvTitle.setText("精致洗车申请");

        new Thread(new Runnable() {
            @Override
            public void run() {
                initJsonData1();
            }
        }).start();

    }

    @OnClick({R.id.img_zheng, R.id.img_fan,R.id.img_license,R.id.rl_shopaddress,R.id.tv_subm})
    public void onViewClicked(View view) {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this);
        switch (view.getId()) {
            case R.id.img_zheng:
                status=2;
                dialogChooseImage.show();
                break;
            case R.id.img_fan:
                status=3;
                dialogChooseImage.show();
                break;
            case R.id.img_license:
                status=1;
                dialogChooseImage.show();
                break;
            case R.id.rl_shopaddress:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                showPickerView();
                break;
            case R.id.tv_subm:
                for (String s:mFileMap.keySet()){
                    mFiles.add(mFileMap.get(s));
                }
                if ( isNull()){
                    initOkGoAddService();
                }
                break;
        }
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items1.get(options1).getPickerViewText() +"-"+
                        options2Items.get(options1).get(options2) +"-"+
                        options3Items.get(options1).get(options2).get(options3);
//                province=options1Items1.get(options1).getArea_id();
//                city=options1Items1.get(options1).getChild().get(options2).getArea_id();
//                county=options1Items1.get(options1).getChild().get(options2).getChild().get(options3).getArea_id();
                //Toast.makeText(AddMyLocationActivity.this, tx, Toast.LENGTH_SHORT).show();
                tvShopaddress.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData1() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "json.json");//获取assets目录下的json文件数据

        ArrayList<Json1Bean> jsonBean = parseData1(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items1 = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> provilist=new ArrayList<>();
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            provilist.add(jsonBean.get(i).getArea_name());

            for (int c = 0; c < jsonBean.get(i).getChild().size(); c++) {//遍历该省份的所有城市
                //                String CityName = ;
                CityList.add(jsonBean.get(i).getChild().get(c).getArea_name());//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getChild().get(c).getChild() == null
                        || jsonBean.get(i).getChild().get(c).getChild().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int j = 0; j < jsonBean.get(i).getChild().get(c).getChild().size(); j++) {
                        City_AreaList.add(jsonBean.get(i).getChild().get(c).getChild().get(j).getArea_name());
                    }

                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            options1Items.addAll(provilist);
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public ArrayList<Json1Bean> parseData1(String result) {//Gson 解析
        ArrayList<Json1Bean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                Json1Bean entity = gson.fromJson(data.optJSONObject(i).toString(), Json1Bean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        Log.e("initUCrop: ", destinationUri + "");

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.main_color));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.main_color));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initMySelfImg(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initMySelfImg(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);

                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                resultUri = RxPhotoTool.cropImageUri;
                if (status == 1) {
                    file1 = roadImageView(resultUri, imgLicense);
                } else if (status==2){
                    file2 = roadImageView(resultUri, imgZheng);
                    mFileMap.put("1",file2);
                }else {
                    file3 = roadImageView(resultUri, imgFan);
                    mFileMap.put("2",file3);
                }
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    if (status == 1) {
                        file1 = roadImageView(resultUri, imgLicense);
                    } else if (status==2){
                        file2 = roadImageView(resultUri, imgZheng);
                        mFileMap.put("1",file2);
                    }else {
                        file3 = roadImageView(resultUri, imgFan);
                        mFileMap.put("2",file3);
                    }
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                RxToast.error(cropError.getMessage());
                Log.e("asd", "initMySelfImg: " + cropError.getMessage());
                break;
            default:
                break;
        }
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {

        Glide.with(this).
                load(uri).
                thumbnail(0.5f).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }

    private void initOkGoAddService() {
        OkGo.<String>post(Config.s + "llc/applyFineCarWashController/applyFineCarWash")
                .tag(this)
                .params("token", UserBean.getbToken(mContext))
                .params("applyName", tvShopname.getText().toString().trim())
                .params("applyTel", etShopphone.getText().toString().trim())
                .params("appAddress", tvShopaddress.getText().toString().trim()+tvShopabstract.getText().toString().trim())
                .params("licFile", file1)
                .addFileParams("idCard", mFiles)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success(baseBean.getOutputMessage());
                            finish();
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    private boolean isNull() {
        if (file1==null){
            RxToast.error("请选择营业执照");
            return false;
        }
        if (TextUtils.isEmpty(tvShopname.getText().toString().trim())) {
            RxToast.error("请输入姓名");
            return false;
        }
        if (TextUtils.isEmpty(etShopphone.getText().toString().trim())) {
            RxToast.error("请填写车牌号码");
            return false;
        }
        if (TextUtils.isEmpty(tvShopaddress.getText().toString().trim())) {
            RxToast.error("请选择地址");
            return false;
        }
        if (TextUtils.isEmpty(tvShopabstract.getText().toString().trim())) {
            RxToast.error("请填写详细地址");
            return false;
        }
        if (mFiles.size() < 2) {
            RxToast.error("请添加完整驾驶证照片");
            return false;
        }
        return true;
    }


}
